﻿using FastJSON;
using FineAdmin.Common;
using FineAdmin.Web.Controllers;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace FineAdmin.Web.Areas.SysSet.Controllers
{
    public class CacheSetController : BaseController
    {
        // GET: SysSet/CacheSet
        public override ActionResult Index(int? id)
        {
         
            return View();
        }

        public ActionResult AjaxGetKey(string key)
        {
            RedisHelper rhelper = new RedisHelper(0);
            var ret = rhelper.StringGet(key);
            return Json(ret, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// 生成缓存
        /// </summary>
        /// <returns></returns>
        public ActionResult AjaxLoadGoods()
        {

            int Count = MaterialGoodsService.CountByWhere("where 1=1 ");
            int page = 1;
            int pagesize = 1000;
            int maxpage = 0;
            maxpage = (int)Math.Ceiling((double)Count / pagesize);
            RedisHelper rhelper = new RedisHelper(1);
            List<KeyValuePair<RedisKey, RedisValue>> kvl = new List<KeyValuePair<RedisKey, RedisValue>>();
            for (int i = 0; i <= maxpage; i++)
            {
                var templist = MaterialGoodsService.GetList(new Model.MaterialGoodsModel(), new Model.PageInfo()
                {
                    page = page,
                    limit = pagesize
                });
                page++;

                foreach (var item in templist)
                {
                    KeyValuePair<RedisKey, RedisValue> keyValuePair = new KeyValuePair<RedisKey, RedisValue>("item:"+"M"+item.Mid+":ItemID" + item.ItemId, JSON.ToJSON(item));
                    KeyValuePair<RedisKey, RedisValue> kv = keyValuePair;
                    kvl.Add(kv);
                }

                rhelper.StringSet(kvl);
                //Thread.Sleep(100); //停一下 避免崩溃
            }



            //foreach (var item in templist)
            //{
            //    //rhelper.StringSet("item_" + item.ItemId, JSON.ToJSON(item));
            //    //rhelper.has

            //}
            //Thread.Sleep(10); //停一下 避免崩溃




            var ret = new AjaxResult()
            {
                state = Common.ResultType.success,
                message = "OK",
                data = Count
            };

            return Json(ret, JsonRequestBehavior.DenyGet);
        }
    }
}